package com.hpp.web;

import java.util.Date;
import java.util.HashMap;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hpp.model.SysRole;
import com.hpp.model.SysUser;
import com.hpp.service.IRoleService;
import com.hpp.service.IUserService;
import com.hpp.utils.Base64Util;
import com.hpp.utils.ConfigUtil;
import com.hpp.utils.DataTableModel;
import com.hpp.utils.DateUtils;
import com.hpp.utils.MD5Util;
import com.hpp.utils.RespJson;
import com.hpp.utils.ResultCode;

@Controller
@RequestMapping(value = "/user")
public class UserController {
	
	private Logger logger = LoggerFactory.getLogger(UserController.class);
	
	@Autowired
	IUserService userService;
	
	@Autowired
	IRoleService roleService;
	
	/**
	 * @Title getUserList  
	 * @Description 获取用户列表
	 * @author hanpp
	 * @param draw
	 * @param start
	 * @param length
	 * @return DataTableModel<?>
	 * @date 2019年1月9日 下午2:36:32  
	 * @throws
	 */
	@ResponseBody
	@RequestMapping(value = "/page/list",method = RequestMethod.POST)
	public DataTableModel<?> getUserList(
			@RequestParam(value = "userName",required = false) String userName,
			@RequestParam(value = "phone",required = false) String phone,
			@RequestParam(value = "roleId",required = false) Integer roleId,
			int draw,int start,int length){
		DataTableModel<SysUser> result = new DataTableModel<SysUser>();
		result.setDraw(draw);
		PageHelper.startPage(start / length + 1, length);
		HashMap<String, Object> map = new HashMap<String,Object>();
		if (StringUtils.isNotBlank(userName)) {
			map.put("userName", userName);
		}
		if (StringUtils.isNotBlank(phone)) {
			map.put("phone", phone);
		}
		if (null != roleId && roleId != -1) {
			map.put("roleId", roleId);
		}
		List<SysUser> list = userService.getUserList(map);
		PageInfo<SysUser> pageList = new PageInfo<SysUser>(list);
		if (pageList != null && pageList.getEndRow() != 0) {
			result.setData(pageList.getList());
			result.setRecordsFiltered(new Long(pageList.getTotal()).intValue());
			result.setRecordsTotal(new Long(pageList.getTotal()).intValue());
		}
		return result;
	}
	
	/***
	 * @Package: com.hpp.web
	 * @Description: 用户名和手机号唯一校验
	 * @author zhoujian
	 * @date 2019年1月15日 下午1:49:48
	 */
	@ResponseBody
	@RequestMapping(value = "/checkUserInfo",method = RequestMethod.POST)
	public RespJson checkUserInfo(
			@RequestParam(value = "userName",required = true) String userName,
			@RequestParam(value = "phone",required = true) String phone){
		List<SysUser> list = userService.checkUserInfo(userName,phone);
		if (null != list && list.size() > 0) {
			return new RespJson(false, "用户名或手机号存在", ResultCode.ERROR, "");
		} else {
			return new RespJson(true, "", ResultCode.SUCCESS, "");
		}
	}
	
	/**
	 * @Title operateSysUser  
	 * @Description 新增、修改用户
	 * @author hanpp
	 * @param id
	 * @param userName
	 * @param userPwd
	 * @param phone
	 * @param roleId
	 * @param realName
	 * @return RespJson
	 * @date 2019年1月11日 下午1:46:23  
	 * @throws
	 */
	@ResponseBody
	@RequestMapping(value = "/operate",method = RequestMethod.POST)
	public RespJson operateSysUser(
			@RequestParam(value = "id",required = false) Integer id,
			@RequestParam(value = "userName",required = true) String userName,
			@RequestParam(value = "userPwd",required = true) String userPwd,
			@RequestParam(value = "phone",required = false) String phone,
			//@RequestParam(value = "roleId",required = true) Integer roleId,
			@RequestParam(value = "realName",required = false) String realName){
		try {
			if (null == id) {
				SysUser user = new SysUser();
				user.setUserName(userName);
				if (StringUtils.isNotBlank(phone)) {
					user.setPhone(phone);
				}
				if (StringUtils.isNotBlank(realName)) {
					user.setRealName(realName);
				}
				//user.setRoleId(roleId);
				user.setUpdateTime(DateUtils.formatDate(new Date(), DateUtils.simple));
				user.setCreateTime(DateUtils.formatDate(new Date(), DateUtils.simple));
				user.setUserPwd(userPwd);
				userService.addSysUser(user);
				return new RespJson(true, "新增成功", ResultCode.SUCCESS, "");
			} else {
				HashMap<String, Object> map = new HashMap<String,Object>();
				map.put("userName", userName);
				SysUser user = userService.getUserInfo(map);
				user.setUserPwd(userPwd);
				if (StringUtils.isNotBlank(phone)) {
					user.setPhone(phone);
				}
				if (StringUtils.isNotBlank(realName)) {
					user.setRealName(realName);
				}
				//user.setRoleId(roleId);
				user.setId(id);
				user.setUpdateTime(DateUtils.formatDate(new Date(), DateUtils.simple));
				userService.updateSysUser(user);
				return new RespJson(true, "修改成功", ResultCode.SUCCESS, "");
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("操作失败：" + e);
			return new RespJson(false, "操作失败", ResultCode.ERROR, "");
		}
		
	}
	
	/**
	 * @Title getUserInfo  
	 * @Description 获取用户信息
	 * @author hanpp
	 * @param id
	 * @return RespJson
	 * @date 2019年1月11日 上午11:44:58  
	 * @throws
	 */
	@ResponseBody
	@RequestMapping(value = "/info",method = RequestMethod.POST)
	public RespJson getUserInfo(
			@RequestParam(value="id",required=true)Integer id){
		try {
			HashMap<String, Object> result = new HashMap<String,Object>();
			HashMap<String, Object> map = new HashMap<String,Object>();
			map.put("id", id);
			SysUser user = userService.getUserInfo(map);
			map.clear();
			List<SysRole> roleList = roleService.getSysRoleList(map);
			result.put("user", user);
			result.put("roleList", roleList);
			user.setUserPwd(null);
			return new RespJson(true, "获取成功", ResultCode.SUCCESS, result);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("获取用户信息失败：" + e);
			return new RespJson(false, "获取失败", ResultCode.ERROR, "");
		}
	}

	/**
	 * @Title deleteSysUser  
	 * @Description 批量删除用户信息
	 * @author hanpp
	 * @param ids
	 * @return RespJson
	 * @date 2019年1月11日 上午11:46:47  
	 * @throws
	 */
	@ResponseBody
	@RequestMapping(value = "/delete",method = RequestMethod.POST)
	public RespJson deleteSysUser(
			@RequestParam(value="ids",required=true)String ids){
		try {
			HashMap<String, Object> map = new HashMap<String,Object>();
			map.put("list", ids.split(","));
			userService.deleteSysUser(map);
			return new RespJson(true, "删除成功", ResultCode.SUCCESS, "");
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("获取用户信息失败：" + e);
			return new RespJson(false, "删除失败", ResultCode.ERROR, "");
		}
	}
	
	/**
	 * @Title resetPwd  
	 * @Description 修改密码
	 * @author hanpp
	 * @param response
	 * @param email
	 * @param userPwd
	 * @param confirmPwd
	 * @return RespJson
	 * @date 2019年1月22日 上午10:48:07  
	 * @throws
	 */
	@ResponseBody
	@RequestMapping(value = "/reset/pwd",method = RequestMethod.POST)
	public RespJson resetPwd(HttpServletResponse response,
			@RequestParam(value = "userId",required = true) String userId,
			@RequestParam(value = "userPwd",required = true) String userPwd,
			@RequestParam(value = "confirmPwd",required = true) String confirmPwd){
		response.setHeader("Access-Control-Allow-Origin", "*");
		try {
			HashMap<String, Object> map = new HashMap<String,Object>();
			map.put("id", userId);
			SysUser user = userService.getUserInfo(map);
			if (!confirmPwd.equals(userPwd)) {
				return new RespJson(false, "请确认密码是否相同", ResultCode.ERROR, "");
			} else {
				user.setUserPwd(userPwd);
				userService.updateSysUser(user);
				return new RespJson(true, "修改成功", ResultCode.SUCCESS, "");
			}
		} catch (Exception e) {
			logger.error("操作失败：" + e);
			return new RespJson(false, "操作失败", ResultCode.ERROR, "");
		}
	}
	
	@ResponseBody
	@RequestMapping(value = "/update",method = RequestMethod.POST)
	public RespJson updateSysUser(HttpServletRequest request,HttpSession session,
			@RequestParam(value = "userName",required = true) String userName,
			@RequestParam(value = "userPwd",required = true) String userPwd){
		try {
			String token = request.getHeader("token");
			SysUser user = (SysUser)session.getAttribute(token);
			user.setUserPwd(userPwd);
			user.setUserName(userName);
			user.setUpdateTime(DateUtils.formatDate(new Date(), DateUtils.simple));
			userService.updateSysUser(user);
			return new RespJson(true, "修改成功", ResultCode.SUCCESS, "");
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("操作失败：" + e);
			return new RespJson(false, "操作失败", ResultCode.ERROR, "");
		}
		
	}
}
